﻿using System;
using System.Collections.Generic;

using System.Text;
using System.IO;

namespace ShapeMergeFactory
{
   public class MergeFactory
    {

        private ShapeFileHead ShapeHead
        {
            get
            {
                throw new System.NotImplementedException();
            }
            set
            {
            }
        }

        private ShapeFileRecord shapeRecord
        {
            get;
            set;
        }

        public MergeFactory()
        {
            shapeRecord = new ShapeFileRecord();
        }

        public void BuildResultFile(string resultFilePath)
        {
            FileStream fileStream = new FileStream(resultFilePath,FileMode.Create,FileAccess.ReadWrite);
            ShapeBinaryWriter shapeBinaryWriter = new ShapeBinaryWriter(fileStream);
            ShapeFileHead resultFileHead = new ShapeFileHead();
            resultFileHead.Write(shapeBinaryWriter);
            fileStream.Close();
        }

        public void MergeShapeHeadAndRecord(string mergeFilePath,string resultFilePath)
        {
            FileStream mergeFileStream = new FileStream(mergeFilePath,FileMode.Open,FileAccess.Read);
            ShapeBinaryReader mergeBinaryReader = new ShapeBinaryReader(mergeFileStream);
            FileStream resultFileStream = new FileStream(resultFilePath,FileMode.Open,FileAccess.Read);
            ShapeBinaryReader resultBinaryReader = new ShapeBinaryReader(resultFileStream);
            ShapeFileHead mergeFileHead = new ShapeFileHead();
            ShapeFileHead resultFileHead = new ShapeFileHead();

            mergeFileHead.Read(mergeBinaryReader);
            resultFileHead.Read(resultBinaryReader);
            resultFileHead.Merge(mergeFileHead);
            resultFileStream.Close();

            FileStream mergeResultFileStream = new FileStream(resultFilePath, FileMode.Open, FileAccess.ReadWrite);
            ShapeBinaryWriter mergeResultBinaryWriter = new ShapeBinaryWriter(mergeResultFileStream);
            resultFileHead.Write(mergeResultBinaryWriter);//覆盖原来的文件头；

            mergeResultBinaryWriter.Seek(0,SeekOrigin.End);
            int currentMergePosition = 0;
            while (currentMergePosition<mergeFileHead.FileLength-100)
            {
                shapeRecord.AddRecord(mergeBinaryReader,mergeResultBinaryWriter);
                currentMergePosition += shapeRecord.shapeRecordHead.recordLength + 4;
            }
            mergeFileStream.Close();
            mergeResultFileStream.Close();
        }
        public void ShapeMergeDelete()
        { 
        }
    }
}
